package com.onlineMIS.ORM.DAO.headQ.user;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.chainS.user.ChainRoleTypeDaoImpl;
import com.onlineMIS.ORM.DAO.chainS.user.ChainStoreDaoImpl;
import com.onlineMIS.ORM.DAO.chainS.user.ChainUserInforService;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.MenuService;
import com.onlineMIS.ORM.entity.chainS.user.ChainRoleType;
import com.onlineMIS.ORM.entity.chainS.user.ChainStore;
import com.onlineMIS.ORM.entity.chainS.user.ChainUserInfor;
import com.onlineMIS.ORM.entity.headQ.HR.PeopleEvaluation;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.Menu;
import com.onlineMIS.ORM.entity.headQ.custMgmt.HeadQCust;
import com.onlineMIS.ORM.entity.headQ.user.RoleFunctionality;
import com.onlineMIS.ORM.entity.headQ.user.SystemRoleMenu;
import com.onlineMIS.ORM.entity.headQ.user.UserFunctionalityDeleted;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.ORM.entity.headQ.user.UserInforVO;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.HttpUtil;
import com.onlineMIS.common.loggerLocal;
import com.onlineMIS.converter.JSONSQLDateConverter;
import com.onlineMIS.filter.SystemFunctionHeadQMapping;
import com.onlineMIS.filter.SystemParm;
import com.opensymphony.xwork2.ActionContext;


@Service
public class UserInforService {
	public final static int LOGIN_SUCCESS = 0;
	public final static int PASSWORD_WRONG = 1;
	public final static int ACCOUNT_DISABLED = 2;
	
	@Autowired
	private UserInforDaoImpl userInforDaoImpl;
	
	@Autowired
	private ChainRoleTypeDaoImpl chainRoleTypeDaoImpl;

	@Autowired
	private SystemRoleMenuDaoImpl systemRoleMenuDaoImpl;
	
	@Autowired
	private MenuService menuService;
	
	@Transactional
	public Response validateUser(String userName, String password){
		Response response = new Response();
		if (userName == null || password == null || userName.equals("") || password.equals("")){
			response.setQuickValue(Response.FAIL, "用户名和密码不能为空");
			return response;
		} 
		
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);
		
		Criterion c1 = Restrictions.eq("user_name", userName);
		if (StringUtils.isNumeric(userName)) 
			c1 = Restrictions.eq("user_id", Integer.parseInt(userName));

		Criterion c2 = Restrictions.eq("password", password);
		criteria = criteria.add(c1).add(c2);
		
		List<UserInfor> user_list = userInforDaoImpl.getByCritera(criteria, false);
		if (user_list != null && user_list.size() != 0){
			UserInfor user = user_list.get(0);
			if (user.getResign() == UserInfor.RESIGNED){
				response.setQuickValue(Response.FAIL, "你的账户已经停用，请联系管理员");
				return response;
			}else {
				userInforDaoImpl.initialize(user);
				response.setReturnCode(Response.SUCCESS);
				response.setReturnValue(user);
			    return response;
			}
		} else {
			response.setQuickValue(Response.FAIL, "登陆用户名或者密码不正确");
			return response;
		}

	}
	
	/**
	 * function to validate the user id and password
	 * @param userId
	 * @param password
	 * @return
	 */
	@Transactional
	public Response validateUser(int userId, String password) {
		Response response = new Response();
		
		if (userId == 0 || password.equals("")){
			response.setQuickValue(Response.FAIL, "用户ID和密码不能为空");
			return response;
		} 
		
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);
		Criterion c1 = Restrictions.eq("user_id", userId);
		Criterion c2 = Restrictions.eq("password", password);
		criteria = criteria.add(c1).add(c2);
		
		List<UserInfor> user_list = userInforDaoImpl.getByCritera(criteria, false);
		if (user_list != null && user_list.size() != 0){
			UserInfor user = user_list.get(0);
			if (user.getResign() == UserInfor.RESIGNED){
				response.setQuickValue(Response.FAIL, "你的账户已经停用，请联系管理员");
				return response;
			}else {
				userInforDaoImpl.initialize(user);
				response.setReturnCode(Response.SUCCESS);
				response.setReturnValue(user);
			    return response;
			}
		} else {
			response.setQuickValue(Response.FAIL, "登陆ID或者密码不正确");
			return response;
		}

	}
	
	public List<UserInfor> getUsersByDept(String deptCode){
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class,"user");
		criteria.add(Restrictions.eq("user.department", deptCode));
		criteria.addOrder(Order.asc("pinyin"));
		
		List<UserInfor> user_list = userInforDaoImpl.getByCritera(criteria, true);
		
		return user_list;
	}

	/**
	 * function to get all user which is normal like not-disabled
	 * @return
	 */
	public List<UserInfor> getAllNormalUsers() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		
		Set<String> departmentSet = new HashSet<String>();
		departmentSet.add(UserInfor.SALES_CODE);
		departmentSet.add(UserInfor.LOGISTIC_CODE);
		departmentSet.add(UserInfor.ACCOUNTANT_CODE);
		criteria.add(Restrictions.in("department", departmentSet));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		
		criteria.addOrder(Order.asc("pinyin"));
		
		List<UserInfor> user_list = userInforDaoImpl.getByCritera(criteria, true);
		
		return user_list;
	}
	
	/**
	 * function to get all users including resgined account
	 * @return
	 */
	public List<UserInfor> getAllUsers() {
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);	
		criteria.add(Restrictions.ne("user_name", "admin"));	
		criteria.addOrder(Order.asc("pinyin"));
		List<UserInfor> user_list = userInforDaoImpl.getByCritera(criteria, true);
		
		return user_list;
	}

	public boolean saveOrUpdate(UserInfor userInfor) {
		boolean isSuccess = true;
		String userName = userInfor.getUser_name();
		
		String userNamePinyin = Common_util.getPinyinCode(userName, false);
		userInfor.setPinyin(userNamePinyin);
		
		//add new user
		if (userInfor.getUser_id() == 0){
			userInforDaoImpl.save(userInfor, true);
		//update user
		} else {
			userInforDaoImpl.update(userInfor, true);
		}
		return isSuccess;
	}

	@Transactional
	public UserInfor getUser(int user_id, boolean initialize) {

		UserInfor userInfor = userInforDaoImpl.get(user_id, true);
		
		if (initialize){
			userInforDaoImpl.initialize(userInfor);
		}
		
		return userInfor;
	}
	


	@Transactional
	public boolean updateUserFunctions(int user_id,List<Integer> functionalities) {
		try{
			/**
			 * remove the original functions
			 */
			userInforDaoImpl.deleteFunctionByUserID(user_id);
			
			/**
			 * add the new function
			 */
			List<UserFunctionalityDeleted> userFunctionalities = new ArrayList<UserFunctionalityDeleted>();
			for (int i = 0; i < functionalities.size(); i++){
				UserFunctionalityDeleted userFunctionality = new UserFunctionalityDeleted();
				userFunctionality.setUser_id(user_id);
				userFunctionality.setFunction_id(functionalities.get(i));
				userFunctionalities.add(userFunctionality);
			}
			
			userInforDaoImpl.addFunctions(userFunctionalities);
		} catch (Exception e) {
			loggerLocal.error(e);
			return false;
		}
		
		return true;
	}

	

	
	/**
	 * to check whether the user name is used before
	 * @param userInfor
	 * @return false：not used; true:used
	 */
	public boolean checkUserName(UserInfor userInfor) {
	    int user_id = userInfor.getUser_id();
	    String user_Name = userInfor.getUser_name();
	    
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class,"user");
		criteria.add(Restrictions.eq("user_name", user_Name));
		
		if (user_id != 0){
			criteria.add(Restrictions.ne("user_id", user_id));	
		}
		
		List<UserInfor> users = userInforDaoImpl.getByCritera(criteria, true);
		
		if (users == null || users.size() == 0)
	       return false;
		else {
			return true;
		}
	}

	/**
	 * UI
	 * to get the users who are evaluaters
	 * 1. all the evaluaters
	 * @return
	 */
	public List<UserInfor> getAvailableEvaluaters() {
        String HQL = "select user from UserInfor user join user.userFunction_Set f where user.user_name <> ? and user.resign =? and f.function_id=? ";

		Object[] values = new Object[]{"admin",UserInfor.NORMAL_ACCOUNT,UserFunctionalityDeleted.CREATE_EVALUATION};
		

		List<UserInfor> user_list = userInforDaoImpl.getByHQL(HQL, values, true);
		
		return user_list;
	}
	


	/**
	 * to get the normal users with ids 
	 * @param ids
	 */
	public List<UserInfor> getUsers(List<Integer> ids) {
		
		DetachedCriteria criteria = DetachedCriteria.forClass(UserInfor.class);
		criteria.add(Restrictions.in("user_id", ids));
		criteria.add(Restrictions.eq("resign", UserInfor.NORMAL_ACCOUNT));
		
		return userInforDaoImpl.getByCritera(criteria, true);
	}


	/**
	 * set the user functions to the objec
	 * @param user
	 */
	public void setFunctions(UserInfor user) {
		//版本1：mapping_hq获取权限
//		DetachedCriteria criteria = DetachedCriteria.forClass(RoleFunctionality.class);	
//		criteria.add(Restrictions.eq("role_id", user.getRoleType()));	
//		List<RoleFunctionality> roleFunctionList = roleFunctionDaoImpl.getByCritera(criteria, false);
//		user.setUserFunctionList(roleFunctionList);		
//		List<Integer> functionIds = new ArrayList<Integer>();
//		if (roleFunctionList.size() >0){
//			for (RoleFunctionality rolef : roleFunctionList) {
//				functionIds.add(rolef.getFunction_id());
//			}			
//		}	
//		user.setFunctions(SystemFunctionHeadQMapping.getFunctionMapping(functionIds));
		
//		//版本2： system_role_menu 获取权限
		List<SystemRoleMenu> systemRoleMenus = systemRoleMenuDaoImpl.selectFunctionsByRoleId(user.getRoleType());	
		user.setSystemRoleMenus(systemRoleMenus);					
		List<String> functions = new ArrayList<String>();
		List<Integer> menuIds = new ArrayList<Integer>();
		if(systemRoleMenus.size() != 0) {
			for (SystemRoleMenu systemRoleMenu : systemRoleMenus) {
				menuIds.add(systemRoleMenu.getMenuId());			
			}
			List<Menu> list = menuService.getMenusByIds(menuIds);
			for (Menu menu : list) {
				functions.add(menu.getMenuPath());
			}
		}		
		user.setFunctions(functions);
	}

	/**
	 * function to update my account from ui
	 * @param loginUser
	 * @param userInfor
	 */
	public UserInfor updateMyAcct(UserInfor logInfor, UserInfor userInfor) {
//		String sql = "update UserInfor u set homePhone=?, mobilePhone=?,idNumber=?,birthday=?, password=? where user_id=?";
//		Object[] parms = new Object[6];
//		parms[0] = userInfor.getHomePhone();
//		parms[1] = userInfor.getMobilePhone();
//		parms[2] = userInfor.getIdNumber();
//		parms[3] = userInfor.getBirthday();
//		parms[4] = userInfor.getPassword();
//		parms[5] = userInfor.getUser_id();
		
//		UserInfor userBean = userInforDaoImpl.get(userInfor.getUser_id(), false);
		
		logInfor.setHomePhone(userInfor.getHomePhone());
		logInfor.setMobilePhone(userInfor.getMobilePhone());
		logInfor.setIdNumber(userInfor.getIdNumber());
		logInfor.setBirthday(userInfor.getBirthday());
		logInfor.setPassword(userInfor.getPassword());

		userInforDaoImpl.update(logInfor, true);
		
		return logInfor;
	}
	
	/**
	 * to create the chainUserInfor by headq
	 * @param loginUserInfor
	 * @return
	 */
	@Transactional
	public ChainUserInfor transferHeadUserToChainUser(UserInfor loginUserInfor) {
		ChainUserInfor chainUserInfor = new ChainUserInfor();
		chainUserInfor.setMobilePhone(loginUserInfor.getMobilePhone());
		chainUserInfor.setName("总部" + loginUserInfor.getName());
		chainUserInfor.setUser_name(loginUserInfor.getUser_name());
		
		//版本1：查询总部人员是否有店铺系统管理员或者连锁店经理的的权限： role_function 中取
//		int chainFunctionType = getUserChainRoleType(loginUserInfor);
//	
//		ChainRoleType adminRoleType = new ChainRoleType();
//		if (chainFunctionType == RoleFunctionality.CHAIN_ADMIN_FUNCTION_TYPE)
//			adminRoleType = chainRoleTypeDaoImpl.get(ChainRoleType.CHAIN_ADMIN, true);
//		else if (chainFunctionType == RoleFunctionality.CHAIN_MGMT_FUNCTION_TYPE)
//			adminRoleType = chainRoleTypeDaoImpl.get(ChainRoleType.CHAIN_MGMT, true);
		
		
		//版本2：查询总部人员是否有店铺系统管理员或者连锁店经理的的权限：从sys_role_menu 中取
		ChainRoleType adminRoleType = new ChainRoleType();
		boolean isChainAdmin = loginUserInfor.getFunctions().contains(RoleFunctionality.CHAIN_ADMIN);
		if (isChainAdmin)
			adminRoleType = chainRoleTypeDaoImpl.get(ChainRoleType.CHAIN_ADMIN, true);
		
		boolean isChainMgmt = loginUserInfor.getFunctions().contains(RoleFunctionality.CHAIN_MGMT);
		if (isChainMgmt)
			adminRoleType = chainRoleTypeDaoImpl.get(ChainRoleType.CHAIN_MGMT, true);				
		
		chainRoleTypeDaoImpl.initialize(adminRoleType);
		
		chainUserInfor.setRoleType(adminRoleType);
		chainUserInfor.setUser_id(ChainUserInfor.CHAIN_ADMIN_USER_ID);
		chainUserInfor.setMyChainStore(ChainStoreDaoImpl.getAllChainStoreObject());
		
		ChainUserInforService.setFunctions(chainUserInfor);
		
		return chainUserInfor;
	}



	public Response validateUser4Chain(String userName, String password) {
		Response response = new Response();
		if (userName == null || password == null || userName.equals("") || password.equals("")){
			response.setQuickValue(Response.FAIL, "用户名和密码不能为空");
			return response;
		} 
		
		String url = SystemParm.getParm("SYSTEM_LOGIN_SERVICE") ;

        // 要传的参数
        String s = null;
        String result = null;
        try {
			s= URLEncoder.encode("formBean.chainUserInfor.user_name", "UTF-8") + "=" +
			           URLEncoder.encode(userName, "UTF-8");
	        s += "&" + URLEncoder.encode("formBean.chainUserInfor.password", "UTF-8") + "=" +
	                URLEncoder.encode(password, "UTF-8");
	        result = HttpUtil.callRemoteService(url, s);
		} catch (Exception e) {
			response.setQuickValue(Response.FAIL, "登陆失败 : " + e.getMessage());
			return response;
		}				

		try {
			JSONObject jsonObject = JSONObject.fromObject(result);

			Response loginResponse = (Response)JSONObject.toBean(jsonObject, Response.class);
			if (loginResponse.getReturnCode() == Response.SUCCESS){
				Object returnValue = loginResponse.getReturnValue();
				JsonConfig jsonConfig = new JsonConfig();
				jsonConfig.setExcludes( new String[]{"activeDate"} );
				jsonObject = JSONObject.fromObject(returnValue,jsonConfig);
				ChainUserInfor userInfor = (ChainUserInfor)JSONObject.toBean(jsonObject, ChainUserInfor.class);

				if (userInfor.getMyChainStore().getAllowAddBarcode() != ChainStore.ALLOW_ADD_BARCODE){
					loginResponse.setQuickValue(Response.FAIL, "你的连锁店没有制作条码的权限，请向总部申请");
				} else {
					if (userInfor.getRoleType().getChainRoleTypeId() != ChainRoleType.CHAIN_OWNER && userInfor.getRoleType().getChainRoleTypeId() != ChainRoleType.CHAIN_LEAD){
						loginResponse.setQuickValue(Response.FAIL, "你的账户没有制作条码的权限，必须是经营者或者店长权限");
					} else 
						loginResponse.setReturnValue(userInfor);
				}
			}
			
			return loginResponse;
		 } catch (Exception e) {
	            e.printStackTrace();
				response.setQuickValue(Response.FAIL, "登陆失败 : " + e.getMessage());
				return response;
		}
	
	}

	public Response getRoles() {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<ChainRoleType> roles = chainRoleTypeDaoImpl.getAll(true);
 		dataMap.put("rows", roles);
	
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	/**
	 * 方便选货人员自动登录，做条码功能
	 * @param userInfor
	 * @return
	 */
	@Transactional
	public Response autoLoginXuanhuo(UserInfor userInfor) {
		Response response = new Response();
		
		String userName = userInfor.getUser_name();
		String password = userInfor.getPassword();
		
		if (password.equals(SystemParm.getAutoLoginMatchCode())) {
			UserInfor userInfor2 = userInforDaoImpl.getUserByUserName(userName);
			if (userInfor2 == null) {
				response.setFail("自动登录失败,无法匹配用户名 : " + userName);
			} else {
				userInforDaoImpl.initialize(userInfor2);
				this.setFunctions(userInfor2);
				response.setReturnCode(Response.SUCCESS);
				response.setReturnValue(userInfor2);
			    return response;
			}
		} else {
			response.setFail("自动登录失败,验证码不匹配");
		}
		
		return response;
	}

	/**
	 * 查询总部会计信息
	 * @return
	 */
	public List<UserInfor> selectAccounting() {
		List<UserInfor> list = userInforDaoImpl.selectAccountings();
		return list;
	}

	
	/**
	 * 查询总部人员信息
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Response selectHqUsers(UserInfor user) {
		Response response = new Response();
		Map dataMap = new HashMap();
		List<UserInforVO> users = new ArrayList<UserInforVO>();
		List<UserInfor>  list = new ArrayList<UserInfor>();
		if (StringUtils.isNotBlank(user.getDepartment()) || user.getRoleType() != Common_util.ALL_RECORD) {
			list = userInforDaoImpl.getUsers(user);
		}else {
			list = getAllUsers();
		}
		for (UserInfor userInfor : list) {
			UserInforVO vo = new UserInforVO();
			vo.setUser_id(userInfor.getUser_id());
			vo.setUser_name(userInfor.getUser_name());
			vo.setPassword(userInfor.getPassword());
			vo.setDepartment(UserInfor.getDepartmentMap().get(userInfor.getDepartment()));
			vo.setMobilePhone(userInfor.getMobilePhone());
			vo.setPinyin(userInfor.getPinyin());
			vo.setResign(userInfor.getResign());
			if (userInfor.getRoleType() !=Common_util.ALL_RECORD_NEW) {
				ChainRoleType roleType = chainRoleTypeDaoImpl.get(userInfor.getRoleType(), true);
				vo.setRoleType(roleType.getChainRoleTypeName());
			}			
			users.add(vo);
		}
		dataMap.put("rows", users);
		response.setReturnValue(dataMap);
		response.setReturnCode(Response.SUCCESS);
		return response;
	}

	public Response createOrUpdateUser(UserInfor userInfor) {
		Response response = new Response();
		
		try {
			//创建新的
			if (userInfor.getUser_id() == Common_util.ALL_RECORD_NEW){
				userInfor.setPassword("888888");
				userInfor.setName(userInfor.getUser_name());
				userInfor.setPinyin(Common_util.getPinyinCode(userInfor.getUser_name(), true));
				userInforDaoImpl.save(userInfor, true);				
		
				response.setSuccess("成功创建新的员工");
			} else {
				//更新员工信息
				UserInfor user = userInforDaoImpl.get(userInfor.getUser_id(), true);
				if (user == null){
					response.setFail("查找原客户信息失败 : 查找Id " + userInfor.getUser_id());
				} else {
					user.setUser_name(userInfor.getUser_name());
					user.setRoleType(userInfor.getRoleType());
					user.setDepartment(userInfor.getDepartment());
					user.setMobilePhone(userInfor.getMobilePhone());
					user.setResign(userInfor.getResign());
					userInforDaoImpl.saveOrUpdate(user, true);
					response.setSuccess("成功更新员工信息");
				}
			}
		} catch (Exception e){
			e.printStackTrace();
			response.setFail("更新员工信息失败 : " + e.getMessage());
		}
		
		return response;
	}

	public Response resetPassWord(UserInfor userInfor) {
		Response response = new Response();
		if (userInfor != null) {
			//更新员工信息
			UserInfor user = userInforDaoImpl.get(userInfor.getUser_id(), true);
			if (user == null){
				response.setFail("查找员工信息失败 : 查找Id " + userInfor.getUser_id());
			}else if (user.getResign() == UserInfor.RESIGNED) {
				response.setFail("该员工已离职，无法重置密码 " + userInfor.getUser_id());
			} else {
				user.setPassword("888888");
				userInforDaoImpl.saveOrUpdate(user, true);
				response.setSuccess("重置密码成功");
			}
		}
		return response;
	}

	



}
